#!/usr/bin/env python
# coding: utf8

"""Celery 异步操作Ansible 服务端"""

import os, sys

if os.environ.get("PYTHONOPTIMIZE", ""):
    print("开始启动")
else:
    print("\33[31m环境变量问题，Celery Client启动后无法正常执行Ansible任务，\n请设置export PYTHONOPTIMIZE=1；\n\33[32mDjango环境请忽略\33[0m")


from celery import Celery
from ansibleWorker.ansibleapi import *
from celery.utils.log import get_task_logger
from kombu import Queue
from ansibleWorker.celeryconfig import BROKER, BACKEND

try:
    from rich import print
except:
    pass

path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, path)

celery_logger = get_task_logger(__name__)

appCelery = Celery("tasks", broker=BROKER, backend=BACKEND)


@appCelery.task(bind=True, name='ansibleWorker.ansibleworker.execplaybooks')
def execplaybooks(self, tid, playbooks, inventory, extra_vars, **kw):
    """tid 必须传入，不能生成"""
    # psources = kw.get('sources') or extra_vars.get('sources') or sources
    print("ansibleWorker.ansibleworker.execplaybooks begin")
    AnsiblePlaybookExecApi29(tid, playbooks, inventory, extra_vars)
    return 'ok'


if __name__ == "__main__":
    appCelery.worker_main()

# celery -A myCelery worker -l info
# celery multi start 1 -A myCelery -l info -c4 --pidfile=tmp/celery_%n.pid -f logs/celery.log
# celery multi restart 1 -A myCelery -l info -c4 --pidfile=tmp/celery_%n.pid -f logs/celery.log
# celery multi stop 1 -A myCelery -l info -c4 --pidfile=tmp/celery_%n.pid
